package cn.gdut.chengcai.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.gdut.chengcai.base.AccountUtil;
import cn.gdut.chengcai.base.ConstantUtil;
import cn.gdut.chengcai.base.EmailUtil;
import cn.gdut.chengcai.base.IdentifyCodeUtil;
import cn.gdut.chengcai.base.JsonUtil;
import cn.gdut.chengcai.base.MemberUtil;
import cn.gdut.chengcai.base.MessageUtil;
import cn.gdut.chengcai.base.RequestUtil;
import cn.gdut.chengcai.base.ResponseData;
import cn.gdut.chengcai.base.UploadDownloadUtil;
import cn.gdut.chengcai.entity.CommentInfo;
import cn.gdut.chengcai.entity.CommentInfoExample;
import cn.gdut.chengcai.entity.MemberInfo;
import cn.gdut.chengcai.entity.MemberInfoExample;
import cn.gdut.chengcai.entity.PersonalInfo;
import cn.gdut.chengcai.entity.UploadInfoEntity;
import cn.gdut.chengcai.enums.EmailTemplateType;
import cn.gdut.chengcai.enums.UploadFileType;
import cn.gdut.chengcai.param.MemberModifyValidateParam;
import cn.gdut.chengcai.service.CommentInfoService;
import cn.gdut.chengcai.service.CourseInfoService;
import cn.gdut.chengcai.service.EmailLogInfoService;
import cn.gdut.chengcai.service.EmailTemplateInfoService;
import cn.gdut.chengcai.service.KeyValueInfoService;
import cn.gdut.chengcai.service.MemberInfoService;
import cn.gdut.chengcai.service.PersonalInfoService;
import cn.gdut.chengcai.vo.MemberInfoVo;
import cn.gdut.chengcai.vo.PersonalInfoVo;

@Controller
@RequestMapping("/member/account")
public class AccountController {

	// public static LogUtil log =
	// LogUtil.getInstance(AuthController.class.getName());

	@Autowired
	protected MemberInfoService memberInfoService;

	@Autowired
	protected PersonalInfoService personalInfoService;

	@Autowired
	protected CourseInfoService courseInfoService;

	@Autowired
	protected EmailLogInfoService emailLogInfoService;

	@Autowired
	protected EmailTemplateInfoService emailTemplateInfoService;

	@Autowired
	protected KeyValueInfoService keyValueInfoService;
	

	@Autowired
	protected CommentInfoService commentInfoService;

	@RequestMapping("/baseInfo")
	public String baseInfo(HttpServletRequest request, HttpSession session, ModelMap map) {
		PersonalInfo person = (PersonalInfo) session.getAttribute("person");
		MemberInfo member = (MemberInfo) session.getAttribute("member");
		PersonalInfoVo personVo = new PersonalInfoVo();
		MemberInfoVo memberVo = new MemberInfoVo();
		try {
			MemberUtil.fillVo(person, personVo);
			MemberUtil.fillVo(member, memberVo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("memberVo", memberVo);
		map.put("personVo", personVo);
		return "/personal/account/baseinfo";
	}

	/**
	 * 保存账号设置操作
	 */

	@RequestMapping("/profileSaveAction")
	public String profileSaveAction(HttpServletRequest request, HttpSession session) {
		MemberInfo member = (MemberInfo) session.getAttribute("member");
		PersonalInfo person = (PersonalInfo) session.getAttribute("person");
		if ((null != member) && (null != person)) {
			person.setProvince(RequestUtil.getParameter(request, "province"));
			person.setCity(RequestUtil.getParameter(request, "city"));
			person.setDistrict(RequestUtil.getParameter(request, "district"));
			person.setStreet(RequestUtil.getParameter(request, "street"));

			// 上传处理
			Map<Integer, UploadInfoEntity> map = UploadDownloadUtil.uploadAction(request, session,
					UploadFileType.PROFILE.getValue(), member.getCreateTime());
			if (null != map && map.size() != 0) {
				String filename = "";
				if (null != map.get(1)) {
					filename = member.getUserAvatarUrl();
					if (StringUtils.isEmpty(filename) == false) {
						UploadDownloadUtil.deleteAction(filename);
					}
					member.setUserAvatarUrl(map.get(1).getFileUrl());
					person.setUserAvatarUrl(map.get(1).getFileUrl());
					CommentInfoExample example = new CommentInfoExample();
					example.createCriteria().andIsDeletedEqualTo(false).andMemberIdEqualTo(member.getId());
					List<CommentInfo> list = commentInfoService.selectByExample(example);
					if((null != list) && (list.size()>0)){
						for(CommentInfo info: list){
							info.setMemberAvatarUrl(member.getUserAvatarUrl());
							commentInfoService.updateByPrimaryKey(info);
						}
					}
				}
			}
			member.setUsername(RequestUtil.getParameter(request, "username"));
			memberInfoService.updateByPrimaryKey(member);
			personalInfoService.updateByPrimaryKey(person);
		} else {
			return "/personal/account/saveFailure";
		}
		return "/personal/account/saveSuccess";
	}

	/**
	 * 账号设置-账号安全
	 */

	@RequestMapping("/accountSafe")
	public String accountSafe(HttpSession session, ModelMap map) {
		MemberInfo member = memberInfoService.selectByPrimaryKey(AccountUtil.getUid(session));
		MemberInfoVo vo = new MemberInfoVo();
		if (member != null) {
			try {
				MemberUtil.fillVo(member, vo);
			} catch (Exception e) {
				e.printStackTrace();
			}
			map.put("entity", vo);
		}
		return "/personal/account/accountSafe";
	}

	/**
	 * 修改密码操作
	 */

	@RequestMapping("/modifyPasswordAction")
	@ResponseBody
	public ResponseData<Object> passwordModifyAction(@RequestBody String jsonString, HttpServletRequest request,
			HttpSession session, ModelMap map) {

		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);

		MemberModifyValidateParam param = (MemberModifyValidateParam) JsonUtil.fromJson(jsonString,
				MemberModifyValidateParam.class);

		if (StringUtils.isEmpty(param.getOldPassword()) == true
				|| StringUtils.isEmpty(param.getNewPassword()) == true) {
			return result;
		}

		try {
			MemberInfo entity = (MemberInfo) session.getAttribute("member");
			if (entity == null) {
				result.setMessage("用户不存在！");
				return result;
			}

			if (!param.getOldPassword().equals(entity.getPassword())) {
				result.setMessage("旧密码不正确！");
				return result;
			}

			entity.setPassword(param.getNewPassword());
			memberInfoService.updateByPrimaryKey(entity);
			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
			// log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 账号设置-账号绑定
	 */

	@RequestMapping("/accountBinding")
	public String accountBinding(HttpSession session, ModelMap map) {
		MemberInfo member = (MemberInfo) session.getAttribute(ConstantUtil.STR_MEMBER);
		MemberInfoVo vo = new MemberInfoVo();
		if (member != null) {
			try {
				MemberUtil.fillVo(member, vo);
			} catch (Exception e) {
				e.printStackTrace();
			}
			map.put("entity", vo);
		}
		return "/personal/account/accountBinding";
	}

	/**
	 * 修改电子邮箱页
	 */
	@RequestMapping("/modify/email")
	public String emailModify(HttpSession session, ModelMap map) {
		MemberInfo entity = (MemberInfo) session.getAttribute(ConstantUtil.STR_MEMBER);
		if (entity != null) {
			map.put("entity", entity);
		}

		// 设置为空，防止保留
		// 修改完邮箱再修改手机号码时，如果没有这句，验证码依旧会保留在session，造成可能用户不用
		// 点击获取验证码而使用上次的验证码
		session.setAttribute(ConstantUtil.SESSION_IDENTIFY_CODE, null);
		return "/personal/account/email/modify";
	}

	/**
	 * 修改电子邮箱操作
	 */
	@RequestMapping("/modifyEmailAction")
	@ResponseBody
	public ResponseData<Object> emailModifyAction(@RequestBody String jsonString, HttpServletRequest request,
			HttpSession session, ModelMap map) {

		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);

		MemberInfo param = (MemberInfo) JsonUtil.fromJson(jsonString, MemberInfo.class);
		try {

			// 判断新邮箱是否已被注册
			MemberInfoExample example = new MemberInfoExample();
			example.createCriteria().andEmailEqualTo(param.getEmail()).andIsDeletedEqualTo(false);
			List<MemberInfo> list = memberInfoService.selectByExample(example);

			if ((null != list) && (list.size() > 0)) {
				result.setMessage(MessageUtil.EMAIL_IS_EXIST_ERROR);
				return result;
			}

			MemberInfo entity = (MemberInfo) session.getAttribute(ConstantUtil.STR_MEMBER);
			entity.setEmail(param.getEmail());
			memberInfoService.updateByPrimaryKey(entity);

			// 更新session
			session.setAttribute(ConstantUtil.STR_MEMBER, entity);

			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
			// log.error(e.getMessage(), e);
		}

		return result;
	}

	/**
	 * 获取邮件验证码
	 */
	@RequestMapping("/getEmailIdentifyCodeAction")
	@ResponseBody
	public ResponseData<Object> getEmailIdentifyCodeAction(@RequestBody String jsonString, HttpServletRequest request,
			HttpSession session, ModelMap map) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);

		MemberInfo entity = (MemberInfo) JsonUtil.fromJson(jsonString, MemberInfo.class);
		if ((null == entity) || ("".equals(entity.getEmail()))) {
			result.setMessage(MessageUtil.EMAIL_IS_NOT_EMPTY);
			return result;
		}

		try {
			String[] args = new String[2];
			args[0] = entity.getEmail();
			args[1] = IdentifyCodeUtil.getRandomNum(6);// 获取六位随机数字

			// 发送邮件
			if (EmailUtil.sendSystemMail(emailLogInfoService, emailTemplateInfoService, keyValueInfoService,
					RequestUtil.getRemoteHost(request), EmailTemplateType.CAPTCHA.getValue(), entity.getEmail(),
					args) == false) {
				result.setMessage(MessageUtil.EMAIL_SEND_FAILURE);
				return result;
			} else {
				session.setAttribute(ConstantUtil.SESSION_IDENTIFY_CODE, args[1]);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setMessage(MessageUtil.SYSTEM_ERROR);
		}
		return result;
	}

}
